jsPlumb.ready(() => {
  const nodeWidth = 100;
  const nodeHeight = 50;

  const canvasEle = document.getElementById('canvas');
  const instance = jsPlumb.newInstance({ container: canvasEle });

  function createNode(left, top) {
    const ele = document.createElement('div');
    ele.className = 'node';
    ele.style.left = `${left}px`;
    ele.style.top = `${top}px`;
    ele.style.width = `${nodeWidth}px`;
    ele.style.height = `${nodeHeight}px`;
    canvasEle.appendChild(ele);
    return ele;
  }

  function createParentNodes(childNodes) {
    const parentNodes = [];
    for (let i = 0; i < childNodes.length; i += 2) {
      const node1 = childNodes[i];
      const node2 = childNodes[i + 1];
      const left = (node1.offsetLeft + node2.offsetLeft) / 2;
      const top = node1.offsetTop - 2 * nodeHeight;
      const parentNode = createNode(left, top);
      instance.connect({
        source: parentNode,
        target: node1,
        anchors: ['Bottom', 'Top'],
        connector: { type: 'Flowchart' },
      });
      instance.connect({
        source: parentNode,
        target: node2,
        anchors: ['Bottom', 'Top'],
        connector: { type: 'Flowchart' },
      });
      parentNodes.push(parentNode);
    }
    if (parentNodes.length > 1) {
      createParentNodes(parentNodes);
    }
  }

  const lastLevelNodes = [];
  for (let i = 0; i < 16; i++) {
    lastLevelNodes.push(createNode(i * nodeWidth * 1.2, 0));
  }

  createParentNodes(lastLevelNodes);

  window.createJsPlumbNavigator(instance);
});
